<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索区 -->
          <el-input
            v-model="queryParams.query"
            placeholder="请输入内容"
            @clear="getUserList"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="queryData"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 第二列 -->
        <el-col :span="4">
          <el-button type="primary" @click="isAddShow = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="180">
        </el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeState(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <!-- 表格操作列 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              @click="showEditDialog(scope.row)"
              type="primary"
              icon="el-icon-edit"
              size="mini"
            >
            </el-button>

            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        @size-change="changeSize"
        @current-change="goPage"
        :current-page="queryParams.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="queryParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户按钮 弹出 对话框 -->
    <el-dialog
      title="新增用户"
      :visible.sync="isAddShow"
      width="50%"
      v-dialogDrag
      @click="closeAddForm"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <!-- 弹出对话框里面的每一项 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 弹出对话框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddShow = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 弹出对话框 编辑用户 -->
    <el-dialog
      title="修改用户"
      :visible.sync="isEditShow"
      width="50%"
      v-dialogDrag
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <!-- 弹出对话框里面的每一项 -->
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 弹出对话框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditShow = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色 弹出对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="isShowDialog"
      width="50%"
      @click="closeRoleDialog"
    >
      <p style="padding-bottom: 8px">用户名：{{ curRole.username }}</p>
      <p style="padding-bottom: 8px">角色名：{{ curRole.role_name }}</p>
      <div>
        分配角色
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowDialog = false">取 消</el-button>
        <el-button type="primary" @click="setUserRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created: function () {
    this.getUserList()
  },
  data () {
    return {
      // 用户数据列表查询参数
      queryParams: {
        query: '',
        pagenum: 1, // 当前页码
        pagesize: 2 // 页容量
      },
      // 用户数组
      userList: [],
      // 用户数据总行数
      total: 0,
      // 控制对话框显示和隐藏
      isAddShow: false,
      // 动态属性
      addForm: {
        username: '',
        password: '',
        emile: '',
        mobile: ''
      },
      // 新增用户弹出对话框 校验规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur']
          }
        ],
        mobile: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: '请输入正确的号码格式',
            trigger: 'blur'
          }
        ]
      },
      // 修改对话框 属性
      isEditShow: false,
      // 修改用户弹出框 数据对象
      editForm: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      // 修改用户对话框 校验规则
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur']
          }
        ],
        mobile: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: '请输入正确的号码格式',
            trigger: 'blur'
          }
        ]
      },
      // 修改角色按钮对话框
      isShowDialog: false,
      // 分配权限时选中的 角色数据对象
      curRole: {},
      // 角色数组(为用户分配角色时使用)
      roleList: [],
      // 为用户设置的选中的 角色id
      selectedRoleId: ''
    }
  },
  methods: {
    // 用户数据列表查询接口
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryParams
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users // 保存在 data对象中
      this.total = res.data.total // 保存数据总行数
    },
    // 切换页容量
    changeSize (newSize) {
      // 将新的页容量设置给查询参数对象
      this.queryParams.pagesize = newSize
      // 重新请求数据
      this.getUserList()
    },
    // 切换 页
    goPage (pageIndex) {
      // 将新的页容量设置给查询参数对象
      this.queryParams.pagenum = pageIndex
      // 重新请求数据
      this.getUserList()
    },
    // 改变用户状态
    async changeState (userData) {
      const { data: resData } = await this.$http.put(
        `user/${userData.id}/state/${userData.mg_state}`
      )
      if (resData.meta.status !== 200) {
        userData.mg_state = !userData.mg_state
        return this.$message.error(resData.meta.msg)
      }
      this.$message.success(resData.meta.msg)
    },
    // 查询按钮
    queryData () {
      this.queryParams.query = this.queryParams.query.trim()
      this.getUserList()
    },
    // 关闭对话框 重置表单内容
    closeAddForm () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户事件
    addUser () {
      this.$refs.addFormRef.validate(async (value) => {
        if (!value) return
        // 调用 新增用户接口 新增数据 并渲染到页面
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('新增失败')
        }
        // eslint-disable-next-line no-lone-blocks
        {
          this.$message.success('新增成功')
          this.isAddShow = false // 关闭对话框窗口
          this.getUserList()
        }
      })
    },
    // 编辑用户信息 弹出框
    showEditDialog (rowData) {
      this.isEditShow = true // 打开对话框
      this.editForm = rowData // 将scope里的数据设置给data
    },
    // 编辑用户 点击事件
    editUser () {
      this.$refs.editFormRef.validate(async (value) => {
        // console.log(value) // 布尔值
        if (!value) return
        // 发起请求 编辑用户接口 传参
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          this.editForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.isEditShow = false
      })
    },
    // 删除用户事件
    delUser (id) {
      this.$messageBox.confirm('确定删除吗？', '系统提示', {
        confirmButtonText: '确定',
        callback: async (action) => {
          if (action === 'cancel') return
          const { data: res } = await this.$http.delete('users/' + id)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getUserList()
        }
      })
    },
    // 分配角色的对话框
    async showRoleDialog (roleData) {
      this.isShowDialog = true
      // 将当前行数据对象(角色数据对象)保存到data.curRole中
      this.curRole = roleData
      // 请求接口
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roleList = res.data
    },
    // 设置用户角色
    async setUserRole () {
      const { data: res } = await this.$http.put(
        `users/${this.curRole.id}/role`,
        { rid: this.selectedRoleId }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.isShowDialog = false
      this.getUserList()
    },
    // 关闭分配角色的对话框
    closeRoleDialog () {
      this.curRole = {}
      this.selectedRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped>
</style>
